# *_*coding:utf-8 *_*
# @Author : Reggie
# @Time : 2021/2/20 下午 4:57 
# *_*coding:utf-8 *_*
import time
from socketserver import ThreadingMixIn
from xmlrpc.server import SimpleXMLRPCServer

from twitter import Twitter


def download(m3u8_url, file_name="", out_path=r"C:\download\twitter"):
    # 使用系统变量修改代理, 可以让m3u8解析也经过代理
    # os.environ["http_proxy"] = "http://127.0.0.1:10809"
    # os.environ["https_proxy"] = "https://127.0.0.1:10809"
    # print(os.environ)

    ts_path = "../tmp"
    proxies = {
        'sock5': '127.0.0.1:10808',
        'http': '127.0.0.1:10809',
        'https': '127.0.0.1:10809'
    }
    # proxies = {}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36'
    }
    download_proxies = proxies
    download_headers = {
        "Referer": "https://twitter.com/home",
        "origin": "https://twitter.com",
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 dingtalk-win/1.0.0 nw(0.14.7) DingTalk(4.6.39-Release.10) Mojo/1.0.0 Native AppType(release)',
    }

    start = time.time()
    M3U8 = Twitter(
        m3u8_url=m3u8_url,
        file_name=file_name,
        out_path=out_path,
        ts_path=ts_path,
        proxies=proxies,
        rm_ts=False,
        headers=headers,
        max_workers=1,
        download_headers=download_headers,
        download_proxies=download_proxies,
        check_all_ts=True,
        merge_ts=True,
        repeat_download=False
    )
    M3U8.run()
    end = time.time()
    print('耗时:', end - start)


def main():
    class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer): pass

    server = ThreadXMLRPCServer(("127.0.0.1", 8889), allow_none=True)  # 初始化
    server.register_function(download, 'download')  # 注册函数2
    print("Listening for Client")
    server.serve_forever()  # 保持等待调用状态


if __name__ == '__main__':
    main()
